<template>
	<view class="container">
		<!-- 省市区三级联动选择器（最终稳定版） -->
		<u-picker 
			:show="show" 
			:columns="cityList" 
			@cancel="close" 
			keyName="name"
			@confirm="confirm" 
			@change="changeHandler" 
			ref="cityPicker"
			title="选择省市区"
		></u-picker>	
	</view>
</template>

<script>
import Api from "@/config/api.js"
export default {
	data() {
		return {
			cityList: [[], [], []], // 省、市、区三列（全量数据）
			show: false,
			rawProvinces: [], // 所有省份原始数据
			currentIndexes: [0, 0, 0] // 手动维护选中索引（核心）
		};
	},
	props: {
		apiParam: {
			type: Object,
			required: true
		}
	},
	methods: {
		// 打开选择器
		open() {
			if (this.rawProvinces.length === 0) {
				this.getFullAreaData();
			} else {
				this.show = true;
			}
		},
		// 关闭选择器
		close() {
			this.show = false;
		},
		// 请求全量省市区数据
		async getFullAreaData() {
			try {
				const res = await Api.commonAddress(this.apiParam);
				if (res.code === 1 && res.data.length) {
					this.rawProvinces = res.data;
					this.initAllColumns();
					this.show = true;
				} else {
					uni.showToast({ title: '地区数据加载失败', icon: 'none' });
				}
			} catch (err) {
				uni.showToast({ title: '接口请求失败', icon: 'none' });
				console.error('地区请求异常：', err);
			}
		},
		// 初始化三列数据
		initAllColumns() {
			// 1. 省份列（全量）
			const allProvinces = this.rawProvinces.map(p => ({ id: p.id, name: p.shortname }));
			this.cityList[0] = allProvinces;

			// 2. 城市列（第一个省份的城市）
			const firstProvince = this.rawProvinces[0];
			const cities = firstProvince?.area_data?.map(c => ({ id: c.id, name: c.shortname })) || [];
			this.cityList[1] = cities;

			// 3. 区县列（第一个城市的区县）
			const firstCity = firstProvince?.area_data?.[0];
			const districts = firstCity?.region_data?.map(d => ({ id: d.id, name: d.shortname })) || [];
			this.cityList[2] = districts;

			// 重置索引
			this.currentIndexes = [0, 0, 0];

			// 更新选择器
			this.$refs.cityPicker?.setColumnValues(0, allProvinces);
			this.$refs.cityPicker?.setColumnValues(1, cities);
			this.$refs.cityPicker?.setColumnValues(2, districts);
		},
		// 加载指定省份的城市
		loadAllCities(province) {
			const cities = province?.area_data?.map(c => ({ id: c.id, name: c.shortname })) || [];
			this.cityList[1] = cities;
			this.$refs.cityPicker?.setColumnValues(1, cities);
			this.currentIndexes[1] = 0; // 重置城市索引
			this.currentIndexes[2] = 0; // 重置区县索引

			// 加载第一个城市的区县
			this.loadAllDistricts(province?.area_data?.[0]);
		},
		// 加载指定城市的区县
		loadAllDistricts(city) {
			const districts = city?.region_data?.map(d => ({ id: d.id, name: d.shortname })) || [];
			this.cityList[2] = districts;
			this.$refs.cityPicker?.setColumnValues(2, districts);
			this.currentIndexes[2] = 0; // 重置区县索引
		},
		// 选择器联动逻辑
		changeHandler(e) {
			const { columnIndex, index } = e;
			this.currentIndexes[columnIndex] = index; // 更新当前列索引

			switch (columnIndex) {
				case 0:
					this.loadAllCities(this.rawProvinces[index]);
					break;
				case 1:
					const province = this.rawProvinces[this.currentIndexes[0]];
					this.loadAllDistricts(province?.area_data?.[index]);
					break;
				case 2:
					break;
			}
		},
		// 确认选择
		confirm() {
			// 从手动维护的索引和列数据中获取选中项
			const province = this.cityList[0][this.currentIndexes[0]] || {};
			const city = this.cityList[1][this.currentIndexes[1]] || {};
			const district = this.cityList[2][this.currentIndexes[2]] || {};

			// 格式化结果
			const result = {
				province,
				city,
				district,
				fullAddress: [province.name, city.name, district.name].filter(Boolean).join(' ')
			};

			this.$emit("confirm", result);
			this.close();
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	/* 无额外样式 */
}
</style>